package com.zzj.controller;

import com.zzj.base.Result;
import com.zzj.service.IFileService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RefreshScope
@RestController
@Log4j2
public class FileController {
    @Value("${system-params.file-save-path}")
    private String filePath;

    @Resource
    private IFileService fileService;

    @Operation(summary = "上传文件", description = "多文件上传")
    @PostMapping("adds")
    public Result add(@RequestParam("files") List<MultipartFile> files) throws IOException {
        if (files.isEmpty()) {
            return Result.error("上传失败，请选择文件");
        }
        List<String> list = new ArrayList<>();
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            String url = fileService.addOne(file, filePath);
            list.add(url);
        }
        return Result.success("多文件上传成功",list);
    }

    @Operation(summary = "上传文件", description = "单文件上传")
    @PostMapping("add")
    public Result add(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return Result.error("上传失败，请选择文件");
        }
        String url = fileService.addOne(file, filePath);
        return Result.success("单文件上传成功",url);
    }
}
